package semaphore;

import java.util.concurrent.Semaphore;


// Semaphore实现线程安全自增一个变量(把信号量为1的Semaphore当作锁来使用)
class Count{
    private int count = 0;

    public Count(){ }

    public void add(){
        count++;
    }
    public int getCount() {
        return count;
    }
}
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Count num = new Count();
        Semaphore semaphore = new Semaphore(1);
        Thread t1 = new Thread(()->{
            for (int i = 0; i < 10000; i++) {
                try {
                    semaphore.acquire();
                    num.add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread t2 = new Thread(()->{
            for (int i = 0; i < 10000; i++) {
                try {
                    semaphore.acquire();
                    num.add();
                    semaphore.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        t1.start();t2.start();
        t1.join();
        t2.join();
        System.out.println(num.getCount());
    }
}
